#!/usr/bin/python

import socket
from bencoding import *
import string
from tracker import *
from types import *

torFile = file("../Desktop/[isoHunt] Lost.S06E06.HDTV.XviD-2HD.torrent")
torInfo = torFile.read()
tran = Bencoding()
torrent = tran.makeBin(torInfo)
track = TrackerRequest(torrent)

info_hash = track.genInfoHash(tran.makeBen(torrent["info"]))
peer_id = track.genPeerId()
connStr = track.genTrackerTuple()

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(connStr)
s.send("GET /announce?"+\
"info_hash=" + track.urlEncode(info_hash) + "&"+\
"peer_id=" + peer_id + "&"+\
"port=6881&uploaded=0&downloaded=0&left=1000000&compact=1&event=started"+\
"HTTP/1.1\r\nHost: " + connStr[0] + "\r\n\r\n")
b = Bencoding()
data = s.recv(1000)
check = ""
while data != check:
    check = data
    data = data + s.recv(1000)
data = data[string.find(data,"\r\n\r\n")+4:len(data)]
binData = b.makeBin(data)
peers = list()
if type(binData['peers']) == StringType:
    peerString = binData['peers']
    ip = ""
    port = ""
    count = 0
    for i in range(len(peerString)):
        if i%6 == 0 and i != 0:
            peers.append((ip, int("0x" + port.replace("0x", ""), 16)))
            ip = ""
            port = ""
        if i%6 <= 2:
            ip = ip + str(ord(peerString[i])) + "."
        elif i%6 == 3:
            ip = ip + str(ord(peerString[i]))
        else:
            port = port + hex(ord(peerString[i]))
peerSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
peerSock.settimeout(5.0)
isConnected = False
peerCount = 0
while not isConnected:
    try:
        peerSock.connect(peers[peerCount])
        isConnected = True
    except socket.timeout:
        print "Test"
        pass
print "Connected!"
handshake = '\023' + "BitTorrent protocol00000000"+info_hash+peer_id
peerSock.send(handshake)
data = peerSock.recv(1000)
print data
check = ""
while data != check:
    check = data
    data = data + peerSock.recv(1000)
print data

#print peers
